import {
    Index
} from './index.model'
import Toast from '@vant/weapp/toast/toast'
const index = new Index()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        stationList: [], // 检车站列表
        cityName: '哈尔滨市',
        latitude: 45.737957,
        longitude: 126.633995,
        markers: [],
        mapHeight: '',
        translateY: 0,
        otherTranslateY: 0,
        changeBtnHidden: false, // 是否隐藏按钮
        cityModel: false
    },
    userLng: 0, // 用户经度
    userLat: 0, // 用户纬度
    otherMarkers: [],
    model: '',

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        let that = this
        //高度自适应
        that._setHeight()
        // 查询所有订单状态
        // that.checkAllSubscribeStatus()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this,
            cityInfo = index.getStorage('cityInfo')
        // that.getTabBar().init() // 切换标签
        that.setData({
            cityName: cityInfo.cityName,
            latitude: cityInfo.latitude,
            longitude: cityInfo.longitude
        })
        that._loadData()
    },

    /**
     * 设置高度
     */
    _setHeight() {
        let that = this,
            windowWidth = wx.getSystemInfoSync().windowWidth,
            windowHeight = wx.getSystemInfoSync().windowHeight,
            rate = 750 / windowWidth,
            mapHeight = windowHeight * rate - 104,
            translateY = mapHeight - 466
        that.model = wx.getSystemInfoSync().model
        if (that.model.search('iPhone X') != -1) {
            // 1344-466    467-439
            translateY = mapHeight - 534
        }
        that.setData({
            mapHeight: mapHeight, // 地图高度
            translateY: translateY, // 面板位置
            otherTranslateY: translateY // 面板位置常量，数值固定不变
        })
    },

    /**
     * 获取所有数据
     */
    _loadData() {
        let that = this
        index.removeStorage('stationList')
        that.authLocation()
        that.mapCtx = wx.createMapContext('myMap')
    },

    /**
     * 授权位置信息
     */
    authLocation() {
        let that = this
        // 位置授权
        index.authLocation().then(() => {
            // 授权后获取用户经纬度
            index.getUserLocation().then((res) => {
                that.userLng = res.longitude
                that.userLat = res.latitude
                // 根据经纬度获取用户地址
                index.getAddress(res.latitude, res.longitude).then((data) => {
                    let address = data.result.address_component,
                        userLocation = {
                            province: address.province,
                            city: address.city,
                            district: address.district,
                        },
                        location = data.result.location,
                        param = {
                            latitude: location.lat,
                            longitude: location.lng,
                            district_id: data.result.ad_info.adcode,
                            cityName: address.city,
                            isSelected: false
                        },
                        cityInfo = index.getStorage('cityInfo')
                    if (!cityInfo || !cityInfo.isSelected) {
                        index.setStorage('cityInfo', param)
                        that.setData(param)
                    }
                    index.setStorage('userLocation', userLocation)
                }).then(() => {
                    that.getCompanyData()
                })
            })
        })
    },

    /**
     * 获取检车站列表
     * @param {string} company_name 检车站名称
     */
    getCompanyData(company_name = '') {
        wx.showLoading({
            title: '正在加载数据',
        })
        let that = this,
            cityInfo = wx.getStorageSync('cityInfo'),
            param = {
                company_name: company_name, // 检车站名称
                userLng: that.userLng, // 用户经度
                userLat: that.userLat, // 用户纬度
                district_id: cityInfo.district_id
            }
        index.getCompanyData(param).then((res) => {
            const data = res.data,
                markers = []
            if (0 == data.length && !cityInfo.isSelected) {
                that.setData({
                    cityModel: true
                })
            }
            index.setStorage('stationList', data)
            for (let i = 0; i < data.length; i++) {
                let marker = {
                    id: data[i]['id'],
                    latitude: data[i]['latitude'],
                    longitude: data[i]['longitude'],
                    title: data[i]['company_name'],
                    iconPath: '/images/index-point.png',
                    width: '60rpx',
                    height: '60rpx',
                    callout: {
                        content: data[i]['company_name'],
                        borderRadius: 12,
                        textAlign: 'center',
                        fontSize: 14,
                        anchorY: -20,
                        padding: 10,
                        display: 'ALWAYS'
                    }
                }
                markers.push(marker)
            }
            that.setData({
                stationList: data,
            })
            that.otherMarkers = markers
        }).then(() => {
            wx.hideLoading()
        })
    },

    /**
     * 搜索检车站
     * @param {*} options
     */
    onSearch(options) {
        wx.showLoading({
            title: '正在加载数据',
        })
        let that = this,
            cityInfo = wx.getStorageSync('cityInfo'),
            param = {
                company_name: options.detail, // 检车站名称
                userLng: that.userLng, // 用户经度
                userLat: that.userLat, // 用户纬度
                district_id: cityInfo.district_id
            }
        index.getCompanyData(param).then((res) => {
            let data = res.data[0],
                markers = [],
                stationList = [],
                latitude = that.data.latitude,
                longitude = that.data.longitude
            if (data) {
                stationList.push(data)
                markers.push({
                    id: data['id'],
                    latitude: data['latitude'],
                    longitude: data['longitude'],
                    title: data['company_name'],
                    iconPath: '/images/index-point.png',
                    width: '60rpx',
                    height: '60rpx',
                    callout: {
                        content: data['company_name'],
                        borderRadius: '20rpx',
                        textAlign: 'center',
                        fontSize: 14,
                        anchorY: -24,
                        padding: 10,
                        display: 'ALWAYS'
                    }
                })
                latitude = data['latitude']
                longitude = data['longitude']
            } else {
                Toast('未搜索到检车站')
            }
            that.setData({
                stationList: stationList,
                markers: markers,
                latitude: latitude,
                longitude: longitude
            })
        }).then(() => {
            wx.hideLoading()
        })
    },

    /**
     * 点击城市
     */
    onTapCity() {
        wx.navigateTo({
            url: '/pages/city/city',
        })
    },

    /**
     * 点击移动面板
     */
    onMovePanel() {
        let that = this,
            translateY = that.data.translateY
        if (translateY == 0) {
            that.setData({
                translateY: that.data.otherTranslateY,
                changeBtnHidden: false
            })
        } else {
            that.setData({
                translateY: 0,
                changeBtnHidden: true
            })
        }
    },

    /**
     * 隐藏面板
     */
    onHidePanel() {
        let that = this,
            translateY = that.data.translateY,
            otherTranslateY = that.data.otherTranslateY
        if (translateY == otherTranslateY) {
            that.setData({
                // 1035rpx 1148rpx 323
                translateY: otherTranslateY + 210,
                markers: that.otherMarkers
            })
        } else {
            that.setData({
                translateY: otherTranslateY,
                markers: []
            })
        }
    },

    /**
     * 点击覆盖物
     * @param {*} options
     */
    onTapMarker(options) {
        wx.navigateTo({
            url: `/pages/station-detail/station-detail?id=${options.markerId}`
        })
    },

    /**
     * 切换到哈尔滨市
     */
    onSwitchCity() {
        let that = this,
            cityInfo = {
                latitude: '45.737957',
                longitude: '126.633995',
                district_id: '230109',
                cityName: '哈尔滨市',
                isSelected: true
            }
        index.setStorage('cityInfo', cityInfo)
        that.setData({
            cityName: cityInfo.cityName,
            latitude: cityInfo.latitude,
            longitude: cityInfo.longitude,
            cityModel: false
        })
        that.getCompanyData()
    },

    /**
     * 关闭申请窗口
     */
    onCloseModel() {
        let that = this,
            cityInfo = index.getStorage('cityInfo')
        that.setData({
            cityModel: false
        });
        if (0 == that.data.stationList.length) {
            // Toast('该城市暂无检车站')
            cityInfo.isSelected = true
            index.setStorage('cityInfo', cityInfo)
        }
    },

    /**
     * 查询所有订单状态
     */
    checkAllSubscribeStatus() {
        let that = this,
            nowTime = Date.parse(new Date()),
            nextTime = wx.getStorageSync('checkAllSubscribeStatus')
        if (nowTime > nextTime) {
            index.checkAllSubscribeStatus().then(() => {
                wx.removeStorageSync('checkAllSubscribeStatus')
                let expire = nowTime + 20 * 60 * 60 * 1000
                wx.setStorageSync('checkAllSubscribeStatus', expire)
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '哈尔滨机动车检测协会提供支持',
            path: '/pages/index/index'
        }
    }
})